<?php
/**
 * Created by PhpStorm.
 * User: frankpian
 * Date: 18-4-19
 * Time: 下午2:09
 */

class LidarController extends CloudControllerBase
{

    public function listLiDARAction()
    {
        if (!$this->isMonitorAdminUser()) {
            $this->returnError($this->lstr("OPERATION_AUTH_ERROR"));
        }
        $action = $this->getRequestAction();
        switch ($action)
        {
            case  $this::REQUEST_ACTION_DELETE: {
            };
                break;
            case  $this::REQUEST_ACTION_LIST: {
                $table = "(SELECT l.*, s.name AS laser_name, i.name AS imu_name, c.nickname FROM lidar AS l 
                            LEFT JOIN laser_scanner_type AS s ON l.laserScannerType_id=s.id
                            LEFT JOIN imu_type AS i ON l.IMUType_id=i.id
                            LEFT JOIN user AS c ON l.checked_user_id=c.id)";
                $this->postQueryByPage(array(
                    "id" => "ID",
                    "lidar_id" => "LiDAR设备编号",
                    "laser_name" => "激光扫描仪类型",
                    "laser_scanner_id" => "激光扫描仪设备ID",
                    "imu_name" => "IMU类型",
                    "imu_type_id" => "IMU设备ID",
                    "check_result_url" => "检校结果",
                    "check_project_url" => "检校工程",
                    "nickname" => "检校人",
                    "checked_at" => "创建时间"
                ), $table
                    , array(
                        ["lidar_id", "like", "%", "%"],
                        ["laser_scanner_id", "like", "%", "%"],
                        ["imu_type_id", "like", "%", "%"],
                        ["laserScannerType_id", "="],
                        ["IMUType_id", "="],
                        ['created_at_start', '>=', '', '', "checked_at"],
                        ['created_at_end', '<=', '', '', "checked_at"]
                    ),"checked_at desc","id");
            };
                break;
        }
        $this->view->setVars(array(
                "firmwareTypeList" => $this->getFirmwareTypeInfo(),
                "IMUTypeList" => $this->getIMUTypeInfo()));
    }

    public function addLiDARAction()
    {
        file_put_contents("./lidar_" . date("Y-m-d") . ".txt",  "\n".date("H:i:s", time()).':'.__METHOD__.':'."recevie HTTP_RAW_POST_DATA:".$GLOBALS['HTTP_RAW_POST_DATA']."\r", FILE_APPEND);
        file_put_contents("./lidar_" . date("Y-m-d") . ".txt",  "\n".date("H:i:s", time()).':'.__METHOD__.':'."recevie POST_DATA:".json_encode($_POST)."\r", FILE_APPEND);
        
        if (!$this->isMonitorAdminUser()) {
            $this->returnError($this->lstr("OPERATION_AUTH_ERROR"));
        }
        $userId=$this->getMonitorLoginUser()->userId;
        $action = $this->getRequestAction();
        switch ($action) {
            case $this::REQUEST_ACTION_ADD:{
                $this->checkRequestParams(array(
                    array(
                        "key" => "lidar_id",
                        "type" => "presence",
                        "message" => "请输入LiDAR设备编号"),
                    array(
                        "key" => "laser_scanner_id",
                        "type" => "presence",
                        "message" => "激光扫描仪设备ID"),
                    array(
                        "key" => "imu_type_id",
                        "type" => "presence",
                        "message" => "IMU设备ID"),
                ));
                $last_id = $this->insertSqlData(array(
                    "table" => "lidar",
                    "fieldList" => array("lidar_id", "laser_scanner_id", "laserScannerType_id", "imu_type_id", "IMUType_id","check_result_url","check_project_url"),
                    "addItems" => array("checked_user_id" => $userId, "checked_at" => date('Y-m-d H:i:s'))
                ));
                if ($last_id>0){
                    $this->returnSuccess("文件上传成功");
                }else{
                    $this->returnError("上传失败！");
                }
            };
                break;
            default:
                $this->view->setVars(array(
                    "laserScannerList" => $this->getLaserScannerTypeInfo(),
                    "IMUTypeList" => $this->getIMUTypeInfo()));
                break;
        }
    }
    
    public function editLiDARAction()
    {
        file_put_contents("./lidar_" . date("Y-m-d") . ".txt",  "\n".date("H:i:s", time()).':'.__METHOD__.':'."recevie POST_DATA:".json_encode($_POST)."\r", FILE_APPEND);
        
        if (!$this->isMonitorAdminUser()) {
            $this->returnError($this->lstr("OPERATION_AUTH_ERROR"));
        }
        $userId=$this->getMonitorLoginUser()->userId;
        $action = $this->getRequestAction();
        switch ($action) {
            case $this::REQUEST_ACTION_UPDATE:{
                $this->checkRequestParams(array(
                        array(
                                "key" => "lidar_id",
                                "type" => "presence",
                                "message" => "请输入LiDAR设备编号"),
                        array(
                                "key" => "laser_scanner_id",
                                "type" => "presence",
                                "message" => "激光扫描仪设备ID"),
                        array(
                                "key" => "imu_type_id",
                                "type" => "presence",
                                "message" => "IMU设备ID"),                        
                ));
                
                $id = $this->getPost("id");
                $sqlId = $this->updateSqlData(array(
                        "table" => "lidar",
                        "fieldList" => array("lidar_id", "laser_scanner_id", "laserScannerType_id", "imu_type_id", "IMUType_id","check_result_url","check_project_url","qualified"),
                        "addItems" => array("review_user_id" => $userId, "review_at" => date('Y-m-d H:i:s')),
                        "where" => " id='$id' "
                ));
                    
                $this->returnSuccess("文件上传成功");
            };
            break;
        default:
            $id= $this->getQuery("id");
            
            $lidar = $this->fetchOne("select * from lidar where id = $id");
            
            $this->view->setVars(array(
                    "laserScannerList" => $this->getLaserScannerTypeInfo(),
                    "IMUTypeList" => $this->getIMUTypeInfo(),
                    "lidar" => $lidar
            ));
            break;
        }
    }

    public function detailLiDARAction()
    {
        if (!$this->isMonitorAdminUser()) {
            $this->returnError($this->lstr("OPERATION_AUTH_ERROR"));
        }
        $action = $this->getRequestAction();
        switch ($action) {
            case $this::REQUEST_ACTION_UPDATE:
            {
                $keyId = $this->getPost("id");
                $sqlId = $this->updateSqlData(array(
                    "table" => "firmware_version",
                    "fieldList" => array("name", "version", "firmware_type_id", "url", "html"),
                    "where" => " id='$keyId' "
                ));
                $this->returnSuccess("发布或保存成功");
//                if ($sqlId){
//                    $this->returnSuccess("发布或保存成功");
//                }else{
//                    $this->returnError("发布或保存失败");
//                }
            }
                break;
            case $this::REQUEST_ACTION_DELETE:
            {
                $data = $this->getPost("filter_list");
                $keyId = json_decode($data, true)["id"];
                $data = $this->fetchOne("SELECT * FROM firmware_version WHERE id=$keyId");
                if ($data["url"]){
                    $this->deleteFileCos($data["url"]);
                }
                $result = $this->deleteOne("firmware_version", array("id"=>$keyId));
                if ($result>0){
                    $this->returnSuccess("删除成功！");
                }else{
                    $this->returnError("删除失败！");
                }
            }
                break;
            default:{
                $keyId = $this->getQuery("id");
                $sql = "SELECT * FROM firmware_version WHERE firmware_version.id=$keyId";
                $keyData = $this->fetchOne($sql);
                $this->view->setVars(array("data"=>$keyData));
                $this->view->setVars(array("firmwareTypeList" => $this->getFirmwareTypeInfo()));
            }
                break;
        }
    }

    public function listLaserScannerTypeAction()
    {
        if (!$this->isMonitorAdminUser()) {
            $this->returnError($this->lstr("OPERATION_AUTH_ERROR"));
        }
        $action = $this->getRequestAction();
        switch ($action) {
            case $this::REQUEST_ACTION_LIST: {
                $pageSize = $this->getPost("page_size");
                $pageNumber = $this->getPost("page_number");
                $pageIndex = ($pageNumber - 1) * $pageSize;
                $tableName = "(SELECT * FROM laser_scanner_type ORDER BY id DESC LIMIT $pageIndex,$pageSize)";
                $result = $this->fetchAll($tableName);
                $this->returnJson($result);
            };
                break;
            case $this::REQUEST_ACTION_UPDATE: {
                $this->checkRequestParams(array(
                    array(
                        "key" => "id",
                        "type" => "presence",
                        "message" => "ID不能为空"),
                    array(
                        "key" => "name",
                        "type" => "presence",
                        "message" => "名称不能为空"),
                ));
                $keyId = $this->getPost("id");
                $sqlId = $this->updateSqlData(array(
                    "table" => "laser_scanner_type",
                    "fieldList" => array("name"),
                    "where" => " id='$keyId' "
                ));
                $this->returnSuccess("更新成功");
            }
                break;
            case $this::REQUEST_ACTION_ADD: {
                $this->checkRequestParams(array(
                    array(
                        "key" => "name",
                        "type" => "presence",
                        "message" => "名称不能为空")
                ));
                $last_id = $this->insertSqlData(array(
                    "table" => "laser_scanner_type",
                    "fieldList" => array("name")
                ));
                if ($last_id >= 0) {
                    $this->returnJson($last_id);
                } else {
                    $this->returnError("添加失败");
                }
            };
                break;
            case $this::REQUEST_ACTION_DELETE: {
                $idList = $this->getPost("id_list");
                $result = $this->deleteAllById("laser_scanner_type", $idList);
                if ($result > 0) {
                    $this->returnSuccess("删除成功！");
                } else {
                    $this->returnError("删除失败！");
                }
            }
                break;
            default: {

            }
                break;
        }
    }
    
    public function listIMUTypeAction()
    {
        if (!$this->isMonitorAdminUser()) {
            $this->returnError($this->lstr("OPERATION_AUTH_ERROR"));
        }
        $action = $this->getRequestAction();
        switch ($action) {
            case $this::REQUEST_ACTION_LIST: {
                $pageSize = $this->getPost("page_size");
                $pageNumber = $this->getPost("page_number");
                $pageIndex = ($pageNumber - 1) * $pageSize;
                $tableName = "(SELECT * FROM imu_type ORDER BY id DESC LIMIT $pageIndex,$pageSize)";
                $result = $this->fetchAll($tableName);
                $this->returnJson($result);
            };
            break;
            case $this::REQUEST_ACTION_UPDATE: {
                $this->checkRequestParams(array(
                        array(
                                "key" => "id",
                                "type" => "presence",
                                "message" => "ID不能为空"),
                        array(
                                "key" => "name",
                                "type" => "presence",
                                "message" => "名称不能为空"),
                ));
                $keyId = $this->getPost("id");
                $sqlId = $this->updateSqlData(array(
                        "table" => "imu_type",
                        "fieldList" => array("name"),
                        "where" => " id='$keyId' "
                ));
                $this->returnSuccess("更新成功");
            }
            break;
            case $this::REQUEST_ACTION_ADD: {
                $this->checkRequestParams(array(
                        array(
                                "key" => "name",
                                "type" => "presence",
                                "message" => "名称不能为空")
                ));
                $last_id = $this->insertSqlData(array(
                        "table" => "imu_type",
                        "fieldList" => array("name")
                ));
                if ($last_id >= 0) {
                    $this->returnJson($last_id);
                } else {
                    $this->returnError("添加失败");
                }
            };
            break;
            case $this::REQUEST_ACTION_DELETE: {
                $idList = $this->getPost("id_list");
                $result = $this->deleteAllById("imu_type", $idList);
                if ($result > 0) {
                    $this->returnSuccess("删除成功！");
                } else {
                    $this->returnError("删除失败！");
                }
            }
            break;
            default: {
                
            }
            break;
        }
    }

    public function getLiDARListAction()
    {
        $sqlType = "SELECT * FROM firmware_type";
        $dataType = $this->fetchAll($sqlType);
        foreach ($dataType AS &$item){
            $typeId = $item["id"];
            $item["info"] = $this->fetchAll("SELECT f.id,f.name,f.version,f.url,f.created_at FROM firmware_version AS f WHERE f.firmware_type_id=$typeId ORDER BY f.created_at DESC");
        }
        if ($dataType){
            $this->returnJson($dataType);
        }else{
            $this->returnError("查询错误");
        }
    }

    public function getLiDARDetailAction()
    {
        $this->checkRequestParams(array(
            array(
                "key" => "id",
                "type" => "presence",
                "message" => "id不存在"),
        ));
        $keyId = $this->getPost("id");
        $data = $this->fetchOne("SELECT * FROM firmware_version WHERE id=$keyId");
        if ($data){
            $this->returnJson($data);
        }else{
            $this->returnError("请求失败");
        }
    }

    public function firmwareDownloadListAction(){
        if($this->isLoginFirmwareCenter() == false){
            $this->response->redirect('../firmware/loginFirmwareCenter');
        }
    }

    public function firmwareDetailAction(){
        if($this->isLoginFirmwareCenter() == false){
            $detailId=$this->getQuery("id");
            $this->response->redirect('../firmware/loginFirmwareCenter?id='.$detailId);
        }
    }

    public function loginFirmwareCenterAction()
    {
        $password = "#feima666";
        if($this->isLoginFirmwareCenter()){
            $this->response->redirect('../firmware/firmwareDownloadList');
        }else{
            $getPwd = $this->getPost("password");
            if ($getPwd){
                if ($getPwd == $password){
                    $this->session->set($this::SESSION_DOWNLOAD_CENTER, true);
                    $this->returnSuccess("登录成功");
                }else {
                    $this->returnError("密码错误");
                }
            }
        }

    }

    public function destorySessionAction()
    {
        $this->session->destroy();
    }
}